import os
import subprocess
import paramiko
import time

# domain_name = "devwx-api.qdingnet.com"
# appname = "qds-partner-api"
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

def ingress_create(domain_name,appname):
    tmpp = """location /qding_appname/ {
        proxy_pass http://ingress;
    }"""
    if os.path.exists("%s/nginx/service_location_conf/%s"%(BASE_DIR,domain_name)):
        print("exists!")
    else:
        print("创建文件")
        os.mkdir("%s/nginx/service_location_conf/%s"%(BASE_DIR,domain_name))

    with open("%s/nginx/service_location_conf/%s/%s.conf"%(BASE_DIR,domain_name,appname),mode="w",encoding="utf-8") as f:
        f.write(tmpp.replace("qding_appname",appname))

# ingress_create("qapstar2.qdingnet.com","qdp-polestar-web")

def sub_ingress_conf(appname):
    aa = "cd %s/nginx/ && git add . && git commit -m '%s' && git push -u origin master"%(BASE_DIR,appname+"_"+str(int(time.time()*100000)))
    obj = subprocess.Popen(aa,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
    print(obj.stdout.read())
    return 1


def rsyn_nginx_git(ip,port,pukey,addr):
    pkey = paramiko.RSAKey.from_private_key_file(pukey)
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    ssh.connect(hostname=ip, port=port, username='root', pkey=pkey)

    stdin, stdout, stderr = ssh.exec_command('cd %s && git pull origin master'%addr)
    print(stdout.read().decode())
    ssh.close()
    return 1


from config import setting
def create_ingress_sync_conf(domain_list,sername):
    for dd in domain_list:
        ingress_create(dd,sername)
    print("===============================")
    sub_ingress_conf(sername)
    print(33333)
    for pp in setting.NGINX_CONF:
        rsyn_nginx_git(pp["ip"], pp["port"], "id_rsa_32", pp["addr"])


def del_ingress_sync_conf(domain_name,sername):
    if os.path.exists("%s/nginx/service_location_conf/%s"%(BASE_DIR,domain_name)):
        print("exists!")
        os.remove("%s/nginx/service_location_conf/%s" % (BASE_DIR, domain_name))
        sub_ingress_conf(sername)

    else:
        print("op")





# create_ingress_sync_conf(["devwx-api.qdingnet.com","devwx-mmm.qdingnet.com"],"qds-partner-api")
# del_ingress_sync_conf("mmm.iqdnet.cn","aaaa")